package com.example.repair_service.controller.user;

import com.example.repair_service.context.BaseContext;
import com.example.repair_service.entity.UserAddressEntity;
import com.example.repair_service.result.Result;
import com.example.repair_service.service.AddressService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/address")
@Tag(name = "C端用户地址簿相关接口")
@Slf4j
public class AddressController {
    @Autowired
    private AddressService addressService;

    /**
     * 查询当前登录用户的所有地址信息
     *
     */
    @GetMapping("/list")
    @Operation(summary = "查询当前登录用户的所有地址信息")
    public Result<List<UserAddressEntity>> list() {
        UserAddressEntity addressBook = new UserAddressEntity();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<UserAddressEntity> list = addressService.list(addressBook);
        return Result.success(list);
    }

    /**
     * 新增地址
     *
     */
    @PostMapping
    @Operation(summary = "新增地址")
    public Result save(@RequestBody UserAddressEntity address) {
        addressService.save(address);
        return Result.success();
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据id查询地址")
    public Result<UserAddressEntity> getById(@PathVariable Long id) {
        UserAddressEntity address = addressService.getById(id);
        return Result.success(address);
    }

    /**
     * 根据id修改地址
     *
     */
    @PutMapping
    @Operation(summary = "根据id修改地址")
    public Result update(@RequestBody UserAddressEntity address) {
        addressService.update(address);
        return Result.success();
    }

    /**
     * 设置默认地址
     *
     */
    @PutMapping("/default")
    @Operation(summary = "设置默认地址")
    public Result setDefault(@RequestBody UserAddressEntity address) {
        addressService.setDefault(address);
        return Result.success();
    }

    /**
     * 根据id删除地址
     *
     */
    @DeleteMapping
    @Operation(summary = "根据id删除地址")
    public Result deleteById(Long id) {
        addressService.deleteById(id);
        return Result.success();
    }

    /**
     * 查询默认地址
     */
    @GetMapping("default")
    @Operation(summary = "查询默认地址")
    public Result getDefault() {
        //SQL:select * from address_book where user_id = ? and is_default = 1
        UserAddressEntity address = new UserAddressEntity();
        address.setIsDefault(true);
        address.setUserId(BaseContext.getCurrentId());
        List<UserAddressEntity> list = addressService.list(address);

        if (list != null && list.size() == 1) {
            return Result.success(list.get(0));
        }

        return Result.error("没有查询到默认地址");
    }
}
